<?php
/*
 module:		轮播图管理
 create_time:	2022-03-08 10:56:46
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use think\App;
use think\exception\ValidateException;
use think\facade\Log;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class PcManage  {

    // 请求参数
    private const KEY_APP_KEY = "appkey";
    private const KEY_FILE_LINK = "file_link";
    private const KEY_VERSION = "version";
    private const KEY_ENABLE_WORDS = "enable_words";
    // 响应参数
    private const KEY_TASK_ID = "TaskId";
    private const KEY_STATUS_TEXT = "StatusText";
    private const KEY_RESULT = "Result";
    // 状态值
    private const STATUS_SUCCESS = "SUCCESS";
    private const STATUS_RUNNING = "RUNNING";
    private const STATUS_QUEUEING = "QUEUEING";
    function submitFileTransRequest($appKey, $fileLink) {
        // 获取task JSON字符串，包含appkey和file_link参数等。
        // 新接入请使用4.0版本，已接入（默认2.0）如需维持现状，请注释掉该参数设置。
        // 设置是否输出词信息，默认为false，开启时需要设置version为4.0。
        $taskArr = array(self::KEY_APP_KEY => $appKey, self::KEY_FILE_LINK => $fileLink, self::KEY_VERSION => "4.0", self::KEY_ENABLE_WORDS => FALSE);
        $task = json_encode($taskArr);
       // print $task . "\n";
        try {
            // 提交请求，返回服务端的响应。
            $submitTaskResponse = AlibabaCloud::nlsFiletrans()
                ->v20180817()
                ->submitTask()
                ->withTask($task)
                ->request();
         //   print $submitTaskResponse . "\n";
            // 获取录音文件识别请求任务的ID，以供识别结果查询使用。
            $taskId = NULL;
            $statusText = $submitTaskResponse[self::KEY_STATUS_TEXT];
            if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
                $taskId = $submitTaskResponse[self::KEY_TASK_ID];
            }
            return $taskId;
        } catch (ClientException $exception) {
            // 获取错误消息
           // print_r( " ClientException".$exception->getErrorMessage());
        } catch (ServerException $exception) {
            // 获取错误消息
           // print_r(" ServerException ".$exception->getErrorMessage());
        }
    }
    function getFileTransResult($taskId) {
        $result = NULL;
        while (TRUE) {
            try {
                $getResultResponse = AlibabaCloud::nlsFiletrans()
                    ->v20180817()
                    ->getTaskResult()
                    ->withTaskId($taskId)
                    ->request();
              //  print " getFileTranresult: 识别查询结果: " . $getResultResponse . "\n";
                $statusText = $getResultResponse[self::KEY_STATUS_TEXT];
                if (strcmp(self::STATUS_RUNNING, $statusText) == 0 || strcmp(self::STATUS_QUEUEING, $statusText) == 0) {
                    // 继续轮询
                    sleep(10);
                }
                else {
                    if (strcmp(self::STATUS_SUCCESS, $statusText) == 0) {
                        $result = $getResultResponse;
                    }
                    // 退出轮询
                    break;
                }
            } catch (ClientException $exception) {
                // 获取错误消息
              // echo "clientException:   "; print_r($exception->getErrorMessage());
            } catch (ServerException $exception) {
                // 获取错误消息
               // echo "serverException:  "; print_r($exception->getErrorMessage());
            }
        }
        return $result;
    }

    //语音识别文字
    function voice_to_text(){
        $accessKeyId ="LTAI5t6x3PvvhSKXDVMsTQMp";
        $accessKeySecret = "Dn1oovqw5lbLu0DbwoY8ltIYFWqJwo";
        $appKey = "6WXRLML9YV5S3GSe";
        $fileLink = "https://gw.alipayobjects.com/os/bmw-prod/0574ee2e-f494-45a5-820f-63aee583045a.wav";
        $fileLink=$_POST["url"];
        /**
         * 第一步：设置一个全局客户端。
         * 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。
         */
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId("cn-shanghai")
            ->asGlobalClient();
        $fileTrans = new PcManage();
        /**
         *  第二步：提交录音文件识别请求，获取任务ID，用于后续的识别结果轮询。
         */
        $taskId = $fileTrans->submitFileTransRequest($appKey, $fileLink);
    /*    if ($taskId != NULL) {
            print "录音文件识别请求成功，task_id: " . $taskId . "\n";
        }
        else {
            print "录音文件识别请求失败!";
            return ;
        }*/
        /**
         * 第三步：根据任务ID轮询识别结果。
         */
        $result = $fileTrans->getFileTransResult($taskId);
        if ($result != NULL) {
            $resultArray = $result->toArray(); // 将 Result 对象转换为数组
            $sentenceText = $resultArray['Result']['Sentences'][0]['Text'];
            return $this->ajaxReturn(200,'返回成功',  $sentenceText);
        }
        else {
            return $this->ajaxReturn(200,  '识别错误');
        }

    }

    //接口返回
    protected function ajaxReturn($status,$msg,$data='',$token=''){
        $res = ['status'=>$status,'msg'=>$msg];
        !empty($data) && $res['data'] = $data;
        !empty($token) && $res['token'] = $token;
        return json($res);
    }


    function get_accesstoken(){
        /**
         * 第一步：设置一个全局客户端
         * 使用阿里云RAM账号的AccessKey ID和AccessKey Secret进行鉴权。
         */

        AlibabaCloud::accessKeyClient(
           "LTAI5t6x3PvvhSKXDVMsTQMp",
           "Dn1oovqw5lbLu0DbwoY8ltIYFWqJwo")
            ->regionId("cn-shanghai")
            ->asDefaultClient();
        try {
            $response = AlibabaCloud::nlsCloudMeta()
                ->v20180518()
                ->createToken()
                ->request();
            $token = $response["Token"];
            if ($token != NULL) {
                date_default_timezone_set('Asia/Shanghai');

                $tokens=$token["Id"];
              return   $this->ajaxReturn(200,'获取成功', $token);
                //print "获取到的token过期时间是：" . $token["ExpireTime"] . "\n";
            }
            else {
                return $this->ajaxReturn(200,'获取失败');
            }
        } catch (ClientException $exception) {
            // 获取错误消息
            return $this->ajaxReturn(201,'获取异常', json_encode($exception->getErrorMessage()));
        } catch (ServerException $exception) {
            // 获取错误消息
            return   $this->ajaxReturn(201,'获取异常', json_encode($exception->getErrorMessage()));
        }
    }
}

